﻿using BestClient;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using RecognitionForm.Core;
using RecognitionForm.Handler;
using SimpleTCP;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Infrastructure.Lib.Core;
using Microsoft.Owin.Hosting;
using Microsoft.AspNet.SignalR.Client;

namespace RecognitionForm
{
    public partial class FrmMain : Inherit_Window.BaseForm
    {
        private SimpleTcpServer server;// = new SimpleTcpServer();
        private Socket clientSocket = null;
        private DataProvider dataProvider = new DataProvider();
        private List<TcpClient> Clients = new List<TcpClient>();
        private string _currentCode;
        private Hashtable htClientStatus = new Hashtable();
        private string _startLogTime = ConfigHelper.GetAppSetting("StartLogTime");
        private string _endLogTime = ConfigHelper.GetAppSetting("EndLogTime");
        private bool _isShowLastLog = Convert.ToBoolean(ConfigHelper.GetAppSetting("IsShowLastLog"));
        private string url;
        private IHubProxy _msgProxy;

        //会议签到接口
        private static HttpHelper _httpHelper = new HttpHelper(ConfigHelper.GetAppSetting("Authorization"), ConfigHelper.GetAppSetting("ipaddress"));
        private static Dictionary<string, string> _headPara = new Dictionary<string, string> {
            {"x-istrong-token",ConfigHelper.GetAppSetting("x-istrong-token")}
        };
        private static string _requestUri = ConfigHelper.GetAppSetting("requestUri");

        private object @lock = new object();

        private CancellationTokenSource cts = new CancellationTokenSource();

        //考勤时钟
        private System.Timers.Timer AttendenceTimer = new System.Timers.Timer(10 * 1000); //设置时间间隔为5秒

        public SynchronizationContext m_SyncContext { get; set; }
        public string devSN { get; set; }
        public Hashtable CachedClients { get; set; }

        public string SaveTxtFileName { get { return string.Format(@"{0}\attendance.txt", Environment.CurrentDirectory); } }

        public FrmMain()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
            CachedClients = new Hashtable();
            devSN = string.Empty;

            //清除txt文本文件
            AttendenceTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            AttendenceTimer.AutoReset = true; //每到指定时间Elapsed事件是触发一次（false），还是一直触发（true）
            AttendenceTimer.Start();
        }

        private void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            var nowTime = Convert.ToDateTime(DateTime.Now.ToString("HH:mm:ss"));
            var startTime = Convert.ToDateTime("00:00:00");
            var endTime = Convert.ToDateTime("00:30:00");

            if (nowTime > startTime && nowTime < endTime)
            {
                String.Empty.WriteTxtLock(FileMode.Create);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FrmAdd addFrm = new FrmAdd();
            //addFrm.Owner = this;
            addFrm.Tag = this;
            addFrm.ShowUpdate += (m) =>
            {
                //发送员工到摄像头
                /*
                List<StaffInfo> persons = new List<StaffInfo>();
                persons.Add(m);
                dynamic rtnObj = new ExpandoObject();
                rtnObj.sid = "ems.common.person.synchronize";
                rtnObj.sys = "response";
                rtnObj.sn = "329916139999";
                rtnObj.code = "00000000";
                rtnObj.message = "ok";
                rtnObj.mid = new Random().Next(-2147483648, 0x7fffffff).ToString();
                rtnObj.payload = new
                {
                    datafmt = "1",
                    persons = persons,
                    count = persons.Count()
                };

                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                Newtonsoft.Json.JsonConvert.SerializeObject(rtnObj, timeFormat);
                 */

                this.BeginInvoke(new Action(() => LoadData()));
            };
            addFrm.ShowDialog();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            LoadData();
            btnStart_Click(sender, e);
        }

        public async void LoadData()
        {
            string depart = txtDepart.Text.Trim();
            if (string.IsNullOrEmpty(depart)) return;

            var data = await dataProvider.GetAllStaffAsync(depart);
            gridStaff.AutoGenerateColumns = false;
            gridStaff.DataSource = data;
            if (data.Count() > 0)
            {
                _currentCode = Convert.ToString(gridStaff.Rows[0].Cells[0].Value);
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            btnDelete.Enabled = false;
            if (await dataProvider.DeleteStaffAsync(new StaffInfo { code = _currentCode }))
            {
                char[] chArray = _currentCode.ToCharArray();
                bool flag = false;
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (chArray[i] > '\x007f')
                    {
                        flag = true;
                    }
                }

                if (flag)
                {
                    MessageBox.Show("人员Id只能由英文字母和数字组成.", "Demo");
                }
                else
                {
                    string[] code = (from s in _currentCode.Split(",".ToCharArray())
                                     where !string.IsNullOrEmpty(s)
                                     select s).ToArray<string>();
                    foreach (string str2 in this.CachedClients.Keys)
                    {
                        if ((this.clientSocket != null) && this.clientSocket.Connected)
                        {
                            string str3 = PersonManager.DeletePerson(code, "2", str2);
                            byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(str3);
                            this.clientSocket = (Socket)this.CachedClients[str2];
                            try
                            {
                                this.clientSocket.Send(BitConverter.GetBytes(bytes.Length));
                                this.clientSocket.Send(bytes);
                                this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), string.Format("从设备{0}删除人员{1}命令下发成功.", this.clientSocket.RemoteEndPoint.ToString(), _currentCode));
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message, "Demo");
                            }
                        }
                    }
                }

                this.BeginInvoke(new Action(() => LoadData()));
            }
            btnDelete.Enabled = true;
        }

        private void gridStaff_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            _currentCode = Convert.ToString(gridStaff.Rows[e.RowIndex].Cells[0].Value);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //btnStart.Enabled = false;

            //var persons = await dataProvider.SynchronizePerson();
            //var response = dataProvider.Recognition();
            //var name = dataProvider.GetStaffName("628ac529c8d74c75b6ee76528c716855").Result;

            //Console.WriteLine(name);

            if (btnStart.Text.IndexOf("开") > 0)
            {
                btnStart.Text = "服务停止";
                cts = new CancellationTokenSource();
                server = new SimpleTcpServer();

                Task.Run(() =>
                 {
                     SocketTask(cts.Token);

                     #region websocket
                     /*
                     string json = Encoding.UTF8.GetString(msg.Data);

                     string saveStr = "";
                     dynamic request = new ExpandoObject();
                     try
                     {
                         request = json.DeserializeObject<dynamic>();
                     }
                     catch (Exception exception1)
                     {
                         Console.WriteLine(exception1.Message);
                     }

                     string sid = Convert.ToString(request.sid);
                     switch (sid)
                     {
                         case "bms.boss.recognition.upload":
                             if (request.payload != null && request.payload.paramList != null)
                             {
                                 var paramList = (request.payload.paramList as IEnumerable<dynamic>).ToList();
                                 paramList.ForEach(p =>
                                 {
                                     saveStr += dataProvider.GetStaffName(Convert.ToString(p.code)).Result + ",";
                                 });
                                 saveStr = saveStr.TrimEnd(',');
                             }

                             //保存识别结果到目录
                             var path = @"C:\DMB-BS3.2.02.38447-finance-win-x86\dmb\ftpserver\home\person\";
                             if (!Directory.Exists(path))
                             {
                                 Directory.CreateDirectory(path);
                             }

                             using (var sw = new StreamWriter(Path.Combine(path, "content.txt"), false))
                             {
                                 sw.WriteLine(saveStr);
                                 sw.Close();
                             }

                             Console.WriteLine(saveStr);

                             var resp = dataProvider.Recognition();
                             msg.Reply(resp);
                             break;

                         case "ems.common.person.synchronize":
                             if (request.code == "00000000")
                             {
                                 Console.WriteLine("人员登记成功");
                             }
                             else
                             {
                                 Console.WriteLine(request.message);
                             }
                             break;
                     }*/
                     #endregion
                 }, cts.Token);

                Task.Run(() => SignalRTask(cts.Token), cts.Token);
            }
            else
            {
                cts.Cancel();
                if (server.IsStarted) server.Stop();
                btnStart.Text = "服务开启";
                Console.WriteLine("服务关闭");
            }

            //                 var wssv = new WebSocketServer(8031);
            //#if DEBUG
            //                 wssv.Log.Level = LogLevel.Trace;
            //#endif

            //                 wssv.AddWebSocketService<PersonWebSocketBehavior>("/");
            //                 wssv.AddWebSocketService<Echo>("/Echo");
            //                 wssv.AddWebSocketService<Chat>("/Chat");

            //                 wssv.Start();
            //                 if (wssv.IsListening)
            //                 {
            //                     Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
            //                     foreach (var path in wssv.WebSocketServices.Paths)
            //                         Console.WriteLine("- {0}", path);
            //                 }

            //                 Console.WriteLine("\nPress Enter key to stop the server...");
            //                 Console.ReadLine();

            //                 wssv.Stop();

            //btnStart.Enabled = true;

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            cts.Cancel();
            if (server != null && server.IsStarted) server.Stop();
        }

        private void SignalRTask(CancellationToken token)
        {
            //创建服务器监听  
            url = "http://*:8000";
            using (WebApp.Start(url))
            {
                Console.WriteLine("SignalR Server runing on {0}", url);

                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        _msgProxy = null;
                        break;
                    }
                    Thread.Sleep(1000);
                }
            }
        }

        private void SocketTask(CancellationToken token)
        {
            if (token.IsCancellationRequested) return;

            var port = 8031;
            server.Start(8031);
            Console.WriteLine("开始监听端口" + port);
            //server.StringEncoder = System.Text.ASCIIEncoding.UTF8;

            server.ClientConnected += (s, tcp) =>
            {
                if (token.IsCancellationRequested)
                {
                    if (server.IsStarted) server.Stop();
                    return;
                }

                var client = tcp;
                if (client.Connected)
                {
                    //Clients.Add(client);
                    m_SyncContext.Post(AddLogMessage, client.Client.RemoteEndPoint.ToString() + "连接成功.");
                }
                /*
                clientSocket = tcp.Client;
                Console.WriteLine(tcp.Client.RemoteEndPoint.ToString() + "连接成功.");
                 */
            };

            server.ClientDisconnected += (s, tcp) =>
            {
                var client = tcp;
                if (!client.Connected)
                {
                    if (Clients.Contains(client)) Clients.Remove(client);
                    m_SyncContext.Post(AddLogMessage, client.Client.RemoteEndPoint.ToString() + "连接断开.");
                }
            };

            server.DataReceived += async (serverSender, msg) =>
            {
                if (token.IsCancellationRequested)
                {
                    if (server.IsStarted) server.Stop();
                    return;
                }

                var s = msg.TcpClient.Client;
                Exception exception;
                this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), "收到来自:" + s.RemoteEndPoint.ToString() + "的消息.");
                this.clientSocket = msg.TcpClient.Client;
                byte[] destinationArray = msg.Data;

                string json = Encoding.UTF8.GetString(destinationArray);
                BestData data = null;
                try
                {
                    data = MessageConverter.fromJson<BestData>(json);
                }
                catch (Exception exception1)
                {
                    exception = exception1;
                    try
                    {
                        this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), exception.Message);
                        //WriteTxtFile(Environment.CurrentDirectory + @"\errorLog.txt", json);
                    }
                    catch (Exception)
                    {
                    }
                    return;
                }
                if (data != null)
                {
                    BestData data2;
                    string str2;
                    byte[] buffer2;
                    int num;
                    this.devSN = data.sn;
                    if (data.sid == "dms.common.device.login")
                    {
                        if (this.CachedClients.Contains(data.sn))
                        {
                            this.CachedClients[data.sn] = s;
                        }
                        else
                        {
                            this.CachedClients.Add(data.sn, s);
                        }
                        data2 = new BestData
                        {
                            sid = "dms.common.device.login",
                            sn = data.sn,
                            sys = "response",
                            mid = new Random().Next(-2147483648, 0x7fffffff).ToString(),
                            code = "00000000",
                            message = "OK."
                        };
                        str2 = MessageConverter.toJson<BestData>(data2);
                        buffer2 = BitConverter.GetBytes(str2.Length);
                        if (!s.Connected) return;
                        s.Send(buffer2);
                        num = s.Send(Encoding.UTF8.GetBytes(str2));
                    }
                    else if (data.sid == "ems.common.person.synchronize")
                    {
                        if (data.code == "00000000")
                        {
                            MessageBox.Show("人员登记成功", "Demo");
                        }
                        else
                        {
                            MessageBox.Show(data.message, "Demo");
                        }
                    }
                    else if (data.sid == "bms.boss.recognition.upload")
                    {
                        try
                        {
                            int num2 = 0;
                            JArray array = (JArray)data.getPayload("paramList");
                            if ((array.Count > 0) && (num2 <= array.Count))
                            {
                                object obj2 = array[num2];
                                if (obj2 is JObject)
                                {
                                    JObject obj3 = obj2 as JObject;
                                    string state = "";
                                    state = (state + string.Format("人员Id:{0},", obj3["pid"].ToString()) + string.Format("性别:{0},", obj3["gender"].ToString())) + string.Format("年龄:{0},", obj3["age"].ToString()) + string.Format("时间:{0}", this.ChangeDTStr(obj3["recognitionTime"].ToString()));
                                    this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), state);

                                    var nowTime = DateTime.Now;
                                    var startTime = Convert.ToDateTime(_startLogTime);
                                    var endTime = Convert.ToDateTime(_endLogTime);

                                    //只在考勤时间内有效
                                    if (nowTime < startTime || nowTime > endTime) return;

                                    //入库
                                    var logInfo = new RecognitionLogInfo
                                    {
                                        staffcode = obj3["pid"].ToString(),
                                        gender = obj3["gender"].ToString(),
                                        age = Convert.ToInt32(obj3["age"]),
                                        recognitionTime = ChangeDT(obj3["recognitionTime"].ToString()),
                                        credate = DateTime.Now
                                    };

                                    //写入txt文件
                                    if (!_isShowLastLog)
                                    {
                                        //判断是否已经记录过了，如果不存在则写入,否则不操作
                                        if (await dataProvider.GetScalarLog(logInfo.staffcode, startTime, endTime) == 0)
                                        {
                                            await dataProvider.InsertRecognitionLogAsync(logInfo);
                                            string staffname = await dataProvider.GetStaffName(logInfo.staffcode);
                                            var appendStr = string.Format("{0}  {1}", logInfo.credate.ToString("yyyy-MM-dd HH:mm:ss"), staffname);
                                            appendStr.WriteTxtLock();

                                            //向web页面新增数据
                                            var appeendList = new List<string> { appendStr };
                                            appeendList.Insert(0, "append");

                                            proxSignalRMessage(appeendList.ObjectToJson());
                                        }
                                    }
                                    else
                                    {
                                        await dataProvider.InsertRecognitionLogAsync(logInfo);
                                        var staffobj = await dataProvider.GetStaffName(logInfo.staffcode);
                                        if (staffobj == null) return;

                                        if (!string.IsNullOrEmpty(staffobj.depart))
                                        {
                                            meetingSiginIn(new { orgName = "四创软件", name = staffobj.name, departmentName = staffobj.depart });
                                        }

                                        //var appendStr = string.Format("<img style='position: absolute;left:20px;top:20px;' width='80px' src='data:image/png;base64,{0}' />{1}  {2}", staffobj.photo, staffobj.depart, staffobj.name);
                                        var appendStr = string.Format("{0}  {1}", staffobj.depart, staffobj.name);
                                        var appeendList = new List<string> { appendStr };
                                        appeendList.Insert(0, "create");
                                        proxSignalRMessage(appeendList.ObjectToJson());

                                        var appendHistoryStr = string.Format("{0}({1}岁)  {2}", staffobj.name, logInfo.age, logInfo.credate.ToString("HH:mm"));
                                        var appeendHistoryList = new List<string> { appendHistoryStr };
                                        appeendHistoryList.Insert(0, "append");
                                        proxSignalRHistoryMessage(appeendHistoryList.ObjectToJson());

                                        /*
                                         * 
                                        //显示最迟一笔记录，重新查询显示
                                        var logList = await dataProvider.GetLastLogs(startTime, endTime);
                                        //向web页面新增数据
                                        if (logList != null && logList.Count() > 0)
                                        {
                                            StringBuilder logSb = new StringBuilder();
                                            foreach (var log in logList)
                                            {
                                                DateTime mtime = Convert.ToDateTime(log.lastTime);
                                                string mname = Convert.ToString(log.name);
                                                logSb.AppendLineFormat("{0}  {1}", mtime.ToString("yyyy-MM-dd HH:mm:ss"), mname);
                                            }
                                            logSb.ToString().WriteTxtLock(FileMode.Create);

                                            //替换web页面数据
                                            var createList = logList.Select(l => string.Format("{0}  {1}", Convert.ToDateTime(l.lastTime).ToString("yyyy-MM-dd HH:mm:ss"), l.name)).ToList();
                                            createList.Insert(0, "create");

                                            proxSignalRMessage(createList.ObjectToJson());
                                        }
                                         */
                                    }

                                    try
                                    {
                                        //WriteTxtFile(SaveTxtFileName, state);
                                    }
                                    catch (Exception exception4)
                                    {
                                        exception = exception4;
                                        this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), exception.Message);
                                    }
                                }
                                try
                                {
                                }
                                catch (Exception exception5)
                                {
                                    exception = exception5;
                                    this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), exception.Message);
                                }
                            }
                        }
                        catch (Exception exception6)
                        {
                            exception = exception6;
                            this.m_SyncContext.Post(new SendOrPostCallback(this.AddLogMessage), exception.Message);
                            //this.listBox1.Items.Add(exception.Message);
                        }
                    }
                    else if (data.sid == "dms.common.device.heartbeat")
                    {
                        if (this.htClientStatus.Contains(this.clientSocket.RemoteEndPoint.ToString()))
                        {
                            this.htClientStatus[this.clientSocket.RemoteEndPoint.ToString()] = DateTime.Now;
                        }
                        else
                        {
                            //this.htClientStatus.Add(this.clientSocket.RemoteEndPoint.ToString(), DateTime.Now);
                        }
                        data2 = new BestData
                        {
                            sid = "dms.common.device.heartbeat",
                            sn = data.sn,
                            sys = "response",
                            mid = new Random().Next(-2147483648, 0x7fffffff).ToString(),
                            code = "00000000",
                            message = "OK."
                        };
                        str2 = MessageConverter.toJson<BestData>(data2);
                        buffer2 = BitConverter.GetBytes(str2.Length);
                        if (!s.Connected) return;
                        s.Send(buffer2);
                        num = s.Send(Encoding.UTF8.GetBytes(str2));
                    }
                    else
                    {
                        //MessageBox.Show(data.message, "Demo");
                    }
                }
            };
        }

        private string ChangeDTStr(string abc)
        {
            //abc = "2017-07-12 11:45:00";
            string ret = "";

            DateTime dt = new DateTime(int.Parse(abc.Substring(0, 4)), int.Parse(abc.Substring(5, 2)),
                int.Parse(abc.Substring(8, 2)), int.Parse(abc.Substring(11, 2)), int.Parse(abc.Substring(14, 2)),
                int.Parse(abc.Substring(17, 2)));

            dt = dt.AddHours(8);

            return dt.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private DateTime ChangeDT(string abc)
        {
            //abc = "2017-07-12 11:45:00";
            string ret = "";

            DateTime dt = new DateTime(int.Parse(abc.Substring(0, 4)), int.Parse(abc.Substring(5, 2)),
                int.Parse(abc.Substring(8, 2)), int.Parse(abc.Substring(11, 2)), int.Parse(abc.Substring(14, 2)),
                int.Parse(abc.Substring(17, 2)));

            dt = dt.AddHours(8);

            return dt;
        }

        private static bool WriteTxtFile(string fileName, string content)
        {
            bool flag = true;
            FileInfo info = new FileInfo(fileName);
            StreamWriter writer = null;
            if (!info.Exists)
            {
                writer = info.CreateText();
            }
            else
            {
                writer = info.AppendText();
            }
            try
            {
                writer.Write(content + Environment.NewLine);
                writer.Flush();
                writer.Close();
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        private void btnSignalRTest_Click(object sender, EventArgs e)
        {
            dynamic rtnObj = new ExpandoObject();
            rtnObj.mode = "append";
            rtnObj.result = new string[] { "abc", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
            Newtonsoft.Json.JsonConvert.SerializeObject(rtnObj);

            var siList = new List<StaffInfo>{
                new StaffInfo{
                    depart = "主任",
                    name = "马云"
                }
            };
            var namelist = siList.Select(s => string.Format("{0}  {1}", s.depart, s.name)).ToList();
            namelist.Insert(0, "create");
            var nameJson = namelist.ObjectToJson();

            meetingSiginIn(new { orgName = "四创软件", name = "陈建华", departmentName = "呈涛大区" });

            proxSignalRMessage(nameJson);
            var historylist = siList.Select(s => string.Format("{0}(16岁)  {1}", s.name, System.DateTime.Now.ToString("HH:mm"))).ToList();
            historylist.Insert(0, "append");
            proxSignalRHistoryMessage(historylist.ObjectToJson());
        }

        private void meetingSiginIn(object entity)
        {
            Task.Run(() =>
            {
                var sigininStr = _httpHelper.Post(entity, _headPara, _requestUri);
                Console.WriteLine(sigininStr);
            });
        }

        private void proxSignalRMessage(string msg)
        {
            if (_msgProxy == null)
            {
                //创建客户端连接  
                string url = "http://127.0.0.1:8000";
                var con = new HubConnection(url, "name=ConsoleClient");

                //var con = new HubConnection(url);
                //实例化客户端代理  
                _msgProxy = con.CreateHubProxy("MsgHub");
                //注册客户端接收  
                _msgProxy.On("receive", (content) =>
                {
                    Console.WriteLine("服务器推送内容：" + content);
                });
                //启动监听并等待  
                con.Start().Wait();
                Console.WriteLine("ConsoleClient,启动成功");
            }

            //new int[] { 1, 2, 3 }.ObjectToJson()

            //客户端，发送内容  
            _msgProxy.Invoke("SendPrivateMessage", "WebClient", msg);
        }

        private void proxSignalRHistoryMessage(string msg)
        {
            if (_msgProxy == null)
            {
                //创建客户端连接  
                string url = "http://127.0.0.1:8000";
                var con = new HubConnection(url, "name=ConsoleClient");

                //var con = new HubConnection(url);
                //实例化客户端代理  
                _msgProxy = con.CreateHubProxy("MsgHub");
                //注册客户端接收  
                _msgProxy.On("receive", (content) =>
                {
                    Console.WriteLine("服务器推送内容：" + content);
                });
                //启动监听并等待  
                con.Start().Wait();
                Console.WriteLine("ConsoleClient,启动成功");
            }

            //new int[] { 1, 2, 3 }.ObjectToJson()

            //客户端，发送内容  
            _msgProxy.Invoke("SendPrivateMessage", "WebHistoryClient", msg);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private async void btnAddPatch_Click(object sender, EventArgs e)
        {
            btnAddPatch.Enabled = false;

            await Task.Run(async () =>
            {

                var path = txtFolderPath.Text.Trim();
                if (string.IsNullOrEmpty(path))
                {
                    MessageBox.Show("路径不能为空！");
                    return;
                }

                if (!FileHelper.IsExistDirectory(path))
                {
                    MessageBox.Show("路径不存在！");
                    return;
                }

                var deaprts = FileHelper.GetDirectories(path);

                foreach (var d in deaprts)
                {
                    var files = FileHelper.GetFileNames(d, "*", false);
                    foreach (var f in files)
                    {
                        string photoBase64 = string.Empty;

                        byte[] bts;
                        //判断文件文件大小，决定是否需要缩略图
                        using (Image imgPhoto = Image.FromFile(f))
                        {
                            if (imgPhoto.Width > 430 || imgPhoto.Width < 230)
                            {
                                using (var thumbImage = ImageHelper.GetThumbnailImageKeepRatio(imgPhoto, 430, 630))
                                {
                                    bts = ImageHelper.Bitmap2Byte(thumbImage as Bitmap);
                                }
                            }
                            else
                            {
                                bts = ImageHelper.GetPhotoBytes(f);
                            }
                        }

                        if (bts != null)
                        {
                            photoBase64 = ImageHelper.GetPhotoBase64(bts);
                        }

                        StaffInfo model = new StaffInfo
                        {
                            code = Guid.NewGuid().ToString("N"),
                            depart = Path.GetFileNameWithoutExtension(d),
                            name = Path.GetFileNameWithoutExtension(f),
                            gender = "M",
                            birthday = DateTime.Now,
                            accAuth = 'Y',
                            groupId = 1,
                            photo = photoBase64
                        };

                        string s = PersonManager.CreatePerson(model.name, model.code, "2", photoBase64, devSN, model.gender);
                        string str4 = string.Format("{0}\r\n", model.code);
                        byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(s);
                        foreach (Socket socket in CachedClients.Values)
                        {
                            if ((socket != null) && socket.Connected)
                            {
                                try
                                {
                                    socket.Send(BitConverter.GetBytes(bytes.Length));
                                    var result = socket.Send(bytes);
                                    if (result <= 0) continue;
                                    await Task.Delay(3700);
                                    m_SyncContext.Post(new SendOrPostCallback(AddLogMessage), string.Format("上传人员到{0}成功.", socket.RemoteEndPoint.ToString()));
                                    await dataProvider.InsertStaffAsync(model);
                                    this.BeginInvoke(new Action(() => LoadData()));
                                }
                                catch (Exception exception)
                                {
                                    MessageBox.Show(exception.Message, "Demo");
                                }
                            }
                        }
                    }
                }
            });

            btnAddPatch.Enabled = true;
        }

        public void AddLogMessage(object message)
        {
            Console.WriteLine(string.Format("{0}:  {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message));
        }

        private void gridStaff_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridViewTextBoxColumn dgv_Text = new DataGridViewTextBoxColumn();
            for (int i = 0; i < gridStaff.Rows.Count; i++)
            {
                int j = i + 1;
                gridStaff.Rows[i].HeaderCell.Value = j.ToString();
            }
        }

        private void gridStaff_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            DataGridViewTextBoxColumn dgv_Text = new DataGridViewTextBoxColumn();
            for (int i = 0; i < gridStaff.Rows.Count; i++)
            {
                int j = i + 1;
                gridStaff.Rows[i].HeaderCell.Value = j.ToString();
            }
        }

    }
}